package cn.knight.user.service.impl;

import cn.knight.basic.constant.BaseConstants;
import cn.knight.basic.exception.BusinessException;
import cn.knight.basic.service.impl.BaseServiceImpl;
import cn.knight.basic.utils.MD5Utils;
import cn.knight.basic.utils.StrUtils;
import cn.knight.basic.vo.EmailRegisterVo;
import cn.knight.basic.vo.RegisterVo;
import cn.knight.user.domain.Logininfo;
import cn.knight.user.domain.User;
import cn.knight.user.mapper.LogininfoMapper;
import cn.knight.user.mapper.UserMapper;
import cn.knight.user.service.IUserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author winnie
 * @since 2022-07-05
 */
@Service
public class UserServiceImpl extends BaseServiceImpl<User> implements IUserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private LogininfoMapper logininfoMapper;

    /**
    * @Title: registerPhone
    * @Description: 根据手机号注册
    * @Author: winnie
    * @Version: 1.0
    * @Date:  7/7/2022 下午11:34
    * @Parameters: [registerVo]
    * @Return void
    */
    @Override
    public void registerPhone(RegisterVo registerVo) {
        // 将参数接出来
        String phone = registerVo.getPhone();
        String phoneCodeValue = registerVo.getPhoneCodeValue();
        String password = registerVo.getPassword();
        String confirmpassword = registerVo.getConfirmpassword();

        // 非空校验
        if (StringUtils.isEmpty(phone)
            || StringUtils.isEmpty(phoneCodeValue)
            || StringUtils.isEmpty(password)
            || StringUtils.isEmpty(confirmpassword)) {
            throw new BusinessException("信息不能为空，请重新填写");
        }

        // 校验两次密码是否正确
        if (!password.equals(confirmpassword)){
            throw new BusinessException("两次输入密码不相同，请重新输入");
        }

        // 校验验证码是否正确
        String phoneCodeKey = BaseConstants.VerifyCodeConstant.BUSINESS_REGISTER_PREFIX + phone;
        Object phoneCodeValueRedis = redisTemplate.opsForValue().get(phoneCodeKey);
        if (phoneCodeValueRedis == null) {
                throw new BusinessException("验证码已过期，请重新获取");
        }
        String phoneValueRedis = phoneCodeValueRedis.toString().split(":")[1];
        if (!phoneValueRedis.equalsIgnoreCase(phoneCodeValue)){
                throw new BusinessException("验证码错误，请重新输入");
        }

        // 用户是否已注册
        User user = userMapper.loadByPhone(phone);
        if (user != null){
            throw new BusinessException("用户已存在，请直接登录");
        }

        user = registerVo2User(registerVo);

        userMapper.save(user);

        Logininfo logininfo = user2Logininfo(user);

        logininfoMapper.save(logininfo);

        user.setLogininfoId(logininfo.getId());

        userMapper.update(user);
    }

    /**
    * @Title: email
    * @Description: 根据邮箱注册
    * @Author: winnie
    * @Version: 1.0
    * @Date:  9/7/2022 上午1:50
    * @Parameters: [emailRegisterDto]
    * @Return void
    */
    @Override
    public void email(EmailRegisterVo emailRegisterVo) {
        String email = emailRegisterVo.getEmail();
        String password = emailRegisterVo.getPassword();
        String confirmPassword = emailRegisterVo.getConfirmPassword();
        //非空
        if (StringUtils.isEmpty(email) ||
                StringUtils.isEmpty(email) ||
                StringUtils.isEmpty(email)){
            throw new BusinessException("参数不能为空");
        }
        User user = userMapper.findByEmail(email);
        if (user !=null){
            throw new BusinessException("邮箱已存在,请直接登录");
        }
        //校验密码是否一致
        if (!password.equals(confirmPassword)){
            throw new BusinessException("密码不一致,请重新输入");
        }
        //初始化user表
        user = emailRegister2User(emailRegisterVo);
        //将user copy给 logininfo
        Logininfo logininfo = user2Logininfo(user);
        logininfoMapper.save(logininfo);
        user.setLogininfoId(logininfo.getId());
        userMapper.save(user);


    }

    private User emailRegister2User(EmailRegisterVo emailRegisterVo) {
        User user = new User();
        user.setUsername(emailRegisterVo.getEmail());
        user.setPhone(emailRegisterVo.getEmail());
        user.setEmail(emailRegisterVo.getEmail());
        String salt = StrUtils.getComplexRandomString(32);
        String saltPassword = MD5Utils.encrypByMd5(salt + emailRegisterVo.getPassword());
        user.setSalt(salt);
        user.setPassword(saltPassword);
        return user;

    }

    /**
    * @Title: loginOut
    * @Description: 退出登录
    * @Author: winnie
    * @Version: 1.0
    * @Date:  9/7/2022 上午1:49
    * @Parameters: [request]
    * @Return void
    */
    @Override
    public void loginOut(HttpServletRequest request) {
        String token = request.getHeader("token");
        redisTemplate.delete(token);
    }


    /**
    * @Title: save
    * @Description: 同步新增数据到logininfo
    * @Author: winnie
    * @Version: 1.0
    * @Date:  6/7/2022 下午7:03
    * @Parameters: [user]
    * @Return void
    */
    @Override
    public void save(User user) {
        initUser(user);
        //登录表信息入库
        Logininfo logininfo = user2Logininfo(user);
        logininfoMapper.save(logininfo);
        // 修改用户的logininfo_id
        user.setLogininfoId(logininfo.getId());
        // 用户信息入库
        userMapper.save(user);

    }

    /**
    * @Title: update
    * @Description: 同步修改数据到logininfo
    * @Author: winnie
    * @Version: 1.0
    * @Date:  6/7/2022 下午7:03
    * @Parameters: [user]
    * @Return void
    */
    @Override
    public void update(User user) {
        initUser(user);
        userMapper.update(user);
        Logininfo logininfo = user2Logininfo(user);
        logininfoMapper.update(logininfo);
    }

    /**
    * @Title: remove
    * @Description: 同步删除数据logininfo
    * @Author: winnie
    * @Version: 1.0
    * @Date:  6/7/2022 下午7:03
    * @Parameters: [id]
    * @Return void
    */
    @Override
    public void remove(Long id) {
        User user = userMapper.loadById(id);
        userMapper.remove(id);
        logininfoMapper.remove(user.getLogininfoId());
    }

    private void initUser(User user) {
        String salt = StrUtils.getComplexRandomString(32);
        String saltPassword = MD5Utils.encrypByMd5(salt + user.getPassword());
        user.setSalt(salt);
        user.setPassword(saltPassword);
    }

    private User registerVo2User(RegisterVo registerVo) {
        String phone = registerVo.getPhone();
        User user = new User();
        user.setUsername(phone);
        user.setPhone(phone);
        String salt = StrUtils.getComplexRandomString(32);
        String saltPassword = MD5Utils.encrypByMd5(salt + registerVo.getPassword());
        user.setPassword(saltPassword);
        user.setSalt(salt);
        return user;
    }

    private Logininfo user2Logininfo(User user) {
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(user, logininfo);
        logininfo.setType(1);
        logininfo.setId(user.getLogininfoId());
        return logininfo;
    }

}
